package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class PrivilegeInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 获取请求头中的token
            String token = request.getHeader(jwtProperties.getApp().getHeaderName());
            //取出token信息
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), AppInfo.class);
            //校验token
            AppInfo app = payload.getUserInfo();
            List<Long> targetList = app.getTargetList();
            //获取当前自己微服务的id
            Long currentServiceId = jwtProperties.getApp().getId();
            //判断是否在targetList访问权限列表中
            if (targetList == null || !targetList.contains(currentServiceId)) {
                log.error("没有访问权限");
                throw new RuntimeException("没有访问权限");
            }
            log.info("【用户微服务】{} 正在访问资源: {}",app.getServiceName(),request.getRequestURI());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【用户微服务】拒绝服务访问, app的token认证失败");
            return false;
        }
    }
}
